package com.teachoa.web;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.teachoa.bean.Order;
import com.teachoa.bean.Project;
import com.teachoa.bean.Task;
import com.teachoa.bean.User;
import com.teachoa.bean.UserTask;
import com.teachoa.constant.Global;
import com.teachoa.enumtype.ProjectStatusEnum;
import com.teachoa.enumtype.SexEnum;
import com.teachoa.enumtype.UserTypeEnum;
import com.teachoa.util.DictUtil;
import com.teachoa.util.IDUtil;
import com.teachoa.util.L;

@SuppressWarnings("rawtypes")
public class ProjectController extends BaseController {
	
	public void add() {
		keepPara("uncertainId");
		renderJsp("project_add.jsp");
	}
	
	@Before(Tx.class)
	public void save() {
		Project pro = getModel(Project.class);
		String id = pro.getStr("id");
		try {
			if(StringUtils.isEmpty(id)) {
				pro.set("id", IDUtil.getId());
				pro.set("status", 0);
				pro.set("user_id", super.getCurrentUserId());
				pro.set("user_name", super.getCurrentUserName());
				pro.set("create_time", new Date());
				pro.save();
			} else 
				pro.update();
			renderJson(success("保存成功！！"));
		} catch (Exception e) {
			e.printStackTrace();
			renderJson(fail("保存失败！！"));
		}
	}
	
	public void index() {
		int pageNo = getParaToInt("pageNo", 1);
		String teacherId = super.getCurrentUserId();
		Page<Project> page = Project.dao.findTeacherProjectsByPage(pageNo, teacherId);
		for(Project p:page.getList()) {
			p.put("status_display", ProjectStatusEnum.getEnumByCode(p.getInt("status")).getDesc());
		}
		setAttr("projectPage", page);
		renderJsp("project.jsp");
	}
	
	public void admin() {
		int pageNo = getParaToInt("pageNo", 1);
		Page<Project> page = Project.dao.findAdminProjectsByPage(pageNo);
		for(Project p:page.getList()) {
			p.put("status_display", ProjectStatusEnum.getEnumByCode(p.getInt("status")).getDesc());
		}
		setAttr("projectPage", page);
		renderJsp("project.jsp");
	}
	
	public void turnpage() {
		int pageNo = getParaToInt("pageNo", 1);
		int type = super.getCurrentUserType();
		Page<Project> page = null;
		if(type==UserTypeEnum.TEACHER.getCode()) {
			String teacherId = super.getCurrentUserId();
			page = Project.dao.findTeacherProjectsByPage(pageNo, teacherId);
		} else if(type==UserTypeEnum.ADMIN.getCode()) {
			page = Project.dao.findAdminProjectsByPage(pageNo);
		}
		for(Project p:page.getList()) {
			p.put("status_display", ProjectStatusEnum.getEnumByCode(p.getInt("status")).getDesc());
		}
		setAttr("projectPage", page);
		renderJsp("project_table.jsp");
	}
	
	@Before(Tx.class)
	public void audit() {
		String projectId = getPara("projectId");
		int isPassed = getParaToInt("isPassed");
		String errorInfo = getPara("errorText");
		try {
			Project.dao.audit(projectId, isPassed, errorInfo);
			renderJson(success("提交成功！！"));
		} catch (Exception e) {
			e.printStackTrace();
			renderJson(fail("提交失败！！"));
		}
	}
	
	public void student() {
		int pageNo = getParaToInt("pageNo", 1);
		String studentId = super.getCurrentUserId();
		Page<Project> page = Project.dao.findStudentProjectsByPage(pageNo, studentId);
		for(Project p:page.getList()) {
			p.put("status_display", ProjectStatusEnum.getEnumByCode(p.getInt("status")).getDesc());
		}
		setAttr("projectPage", page);
		renderJsp("project_student.jsp");
	}
	
	public void studentPage() {
		int pageNo = getParaToInt("pageNo", 1);
		String studentId = super.getCurrentUserId();
		Page<Project> page = Project.dao.findStudentProjectsByPage(pageNo, studentId);
		for(Project p:page.getList()) {
			p.put("status_display", ProjectStatusEnum.getEnumByCode(p.getInt("status")).getDesc());
		}
		setAttr("projectPage", page);
		renderJsp("project_student_table.jsp");
	}
	
	//项目申请审核
	@Before(Tx.class)
	public void proApply() {
		Project project = new Project();
		project.set("id", getPara());
		project.set("status", ProjectStatusEnum.PROWAIT.getCode());
		try {
			project.update();
			renderJson(success("提交成功！！"));
		} catch (Exception e) {
			e.printStackTrace();
			renderJson(fail("提交失败！！"));
		}
	}
	
	@Before(Tx.class)
	public void update() {
		setAttr("project", Project.dao.findById(getPara()));
		renderJsp("project_add.jsp");
	}
	
	public void check() {
		boolean flag = Project.dao.findProjectByName(getPara("name"));
		if(flag)
			renderJson(success(null));
		else 
			renderJson(fail("项目名不能重复！！"));
	}
	
	/**************************team****************************/
	
	public void team() {
		String projectId = getPara();
		String flowId = Project.dao.getFlowIdByProjectId(getPara());
		setAttr("projectId", projectId);
//		List<WorkModel> list = getSnakerEngine().process().getProcessById(flowId)
//			.getModel().getWorkModels();
		List<Task> list = Task.dao.findTasksByProcessId(flowId);
		setAttr("nodes", list);
		
		Page<User> studentPage = User.dao.getUserPageByType(1, UserTypeEnum.STUDENT.getCode());
		Map<Integer, String> gradeMap = DictUtil.getDictMapByPath(Global.gradePath);
		Map<Integer, String> majorMap = DictUtil.getDictMapByPath(Global.majorPath);
		for(User student:studentPage.getList()) {
			student.put("sex_display", SexEnum.getEnumByCode(student.getInt("sex")).getDesc());
			student.put("grade_display", gradeMap.get(student.getInt("grade")));
			student.put("major_display", majorMap.get(student.getInt("major")));
		}
		setAttr("studentPage", studentPage);
		
		setAttr("grades", DictUtil.getSubDictsByPath(Global.gradePath));
		setAttr("majors", DictUtil.getSubDictsByPath(Global.majorPath));
		renderJsp("team.jsp");
	}
	
	public void loadNodeMember() {
		String projectId = getPara("projectId");
		String taskId = getPara("taskId");
		setAttr("users", UserTask.dao.getUsersByPidAndTaskId(projectId, taskId));
		keepPara("projectId");
		renderJsp("team_member.jsp");
	}
	
	@Before(Tx.class)
	public void teamMemberRemove() {
		try {
			UserTask.dao.deleteById(getPara());
			renderJson(success("移除成功！！"));
		} catch (Exception e) {
			e.printStackTrace();
			renderJson(fail("移除失败！！"));
		}
	}
	
	@Before(Tx.class)
	public void teamDistribute() {
		UserTask ut = getModel(UserTask.class);
		ut.set("id", IDUtil.getId());
		ut.set("is_current_node", 0);//默认不是当前所处节点
		try {
			ut.save();
			renderJson(success("分配成功！！"));
		} catch (Exception e) {
			e.printStackTrace();
			renderJson(fail("分配失败！！"));
		}
	}
	
	@Before(Tx.class)
	public void teamFinishBuild() {
		try {
			Project.dao.updateStatus(getPara(), ProjectStatusEnum.TEAM.getCode());
			renderJson(success("创建成功！！"));
		} catch (Exception e) {
			e.printStackTrace();
			renderJson(fail("创建失败！！"));
		}
	}
	
	@Before(Tx.class)
	public void teamApply() {
		try {
			Project.dao.updateStatus(getPara(), ProjectStatusEnum.TEAMWAIT.getCode());
			renderJson(success("申请成功！！"));
		} catch (Exception e) {
			e.printStackTrace();
			renderJson(fail("申请失败！！"));
		}
	}
	
	public void teamView() {
		String projectId = getPara();
		String processId = Project.dao.getFlowIdByProjectId(projectId);
		List<Task> list = Task.dao.findTasksByProcessId(processId);
		setAttr("nodes", list);
		setAttr("projectId", projectId);
//		Process process = super.getSnakerEngine().process().getProcessById(processId);
//		List<WorkModel> wms = process.getModel().getWorkModels();
//		setAttr("nodes", wms);
//		setAttr("projectId", projectId);
		renderJsp("team_audit.jsp");
	}
	
	@Before(Tx.class)
	public void teamAudit() {
		String projectId = getPara("projectId");
		int isPassed = getParaToInt("isPassed");
		Project project = new Project();
		project.set("id", projectId);
		int status = isPassed==1?ProjectStatusEnum.TEAMSUCCESS.getCode():
			ProjectStatusEnum.TEAM.getCode();
		project.set("status", status);
		try {
			project.update();
			renderJson(success("提交成功！！"));
		} catch (Exception e) {
			e.printStackTrace();
			renderJson(fail("提交失败！！"));
		}
	}
	
	public void teamUser() {
		Page<User> studentPage = User.dao.getUserPageByType(getParaToInt("pageNo", 1), UserTypeEnum.STUDENT.getCode());
		Map<Integer, String> gradeMap = DictUtil.getDictMapByPath(Global.gradePath);
		Map<Integer, String> majorMap = DictUtil.getDictMapByPath(Global.majorPath);
		for(User student:studentPage.getList()) {
			student.put("sex_display", SexEnum.getEnumByCode(student.getInt("sex")).getDesc());
			student.put("grade_display", gradeMap.get(student.getInt("grade")));
			student.put("major_display", majorMap.get(student.getInt("major")));
		}
		setAttr("studentPage", studentPage);
		renderJsp("team_user.jsp");
	}
	
	/**
	 * 流程启动
	 */
	@Before(Tx.class)
	public void start() {
		String projectId = getPara();
		Project project = new Project();
		project.set("id", projectId);
		int status = ProjectStatusEnum.START.getCode();
		project.set("status", status);
		try {
			//String processId = Project.dao.getFlowIdByProjectId(projectId);
			Order order = new Order();
			String orderId = IDUtil.getId();
			order.set("id", orderId);
			order.set("project_id", projectId);
			order.set("node", 1);
			order.save();
//			List<Record> list = UserTask.dao.getUsersByPidAndNode(projectId, 1);
//			String[] userIds = new String[list.size()];
//			for(int i=0;i<userIds.length;i++) {
//				String userId = list.get(i).getStr("user_id");
//				userIds[i] = userId;
//			}
//			Order order = super.getSnakerEngine().startInstanceById(processId, super.getCurrentUserId()
//					, Maps.newHashMap("1", userIds));
			project.set("order_id", orderId);
			project.update();
			UserTask.dao.updateCurrentNodeByPidAndNode(projectId, 1);
			renderJson(success("启动成功！！"));
		} catch (Exception e) {
			e.printStackTrace();
			renderJson(fail("启动失败！！")); 
		}
	}
	
	public void detail() {
		setAttr("project", Project.dao.findProjectDetail(getPara()));
		renderJsp("project_detail.jsp");
	}
	
	public void del() {
		try {
			Project.dao.deleteById(getPara());
			renderJson(success("删除成功！！"));
		} catch (Exception e) {
			e.printStackTrace();
			renderJson(fail("删除失败！！"));
		}
	}
	
	
	
	
	
	
	
	
	
	public void publish() {
		renderJsp("publish.jsp");
	}
	
	public void name() {
		renderJsp("name.jsp");
	}
	
	public void project() {
		renderJsp("project.jsp");
	}
	
	public void ask() {
		Map user = getSessionAttr("user");
		int type = L.toInt(user.get("type"));
		if(type==2) 
			renderJsp("ask/student.jsp");
		else if(type==3)
			renderJsp("ask/expert.jsp");
	}
	
}
